#include <iostream>
#include <string> 
#include <ctime>
#include <unistd.h>
#include "RingQueue.hpp"
#include "task.hpp"

using namespace std;

struct threaddata
{
    ringqueue<Task> *rq;
    string threadname;
};

void* Consumer(void* arg)
{
    threaddata *td = static_cast<threaddata *>(arg);
    ringqueue<Task> *rq = td->rq;
    while(true)
    {
        //消费任务
        Task t;
        rq->pop(&t);
        //处理任务
        t();
        cout << td->threadname << "处理任务:" << t.GetTask() << " 结果：" << t.GetResult() << endl;
    }
}

void* Producer(void* arg)
{
    threaddata *td = static_cast<threaddata *>(arg);
    ringqueue<Task> *rq = td->rq;
    int len = opers.size();
    while(true)
    {
        //模拟获取任务
        char op = opers[rand()%len];
        int x = rand() % 10 + 1;
        usleep(10);
        int y = rand() % 10;
        Task t(x, y, op);
        //生产任务
        rq->push(t);
        cout << td->threadname << "生产任务：" << t.GetTask() << endl;
        sleep(1);
    }
}

int main()
{
    srand(time(nullptr)/3);
    ringqueue<Task> *rq = new ringqueue<Task>(5);
    pthread_t c[3];
    pthread_t p[5];
    for(int i = 0; i < 3; ++i)
    {
        threaddata *td = new threaddata;
        td->rq = rq;
        td->threadname = "Consumer-" + to_string(i); 
        pthread_create(c+i, nullptr, Consumer, td);
    }
    for(int i = 0; i < 5; ++i)
    {
        threaddata *td = new threaddata;
        td->rq = rq;
        td->threadname = "Producer-" + to_string(i); 
        pthread_create(p+i, nullptr, Producer, td);
    }
    
    for(int i = 0; i < 3; ++i)
    {
        pthread_join(c[i], nullptr);
    }
    for(int i = 0; i < 5; ++i)
    {
        pthread_join(p[i], nullptr);
    }
    
    delete rq;
    return 0;
}